package huaweiExam;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class main3 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.setLeft(new TreeNode(9));
        root.setRight(new TreeNode(18));
        root.getRight().setLeft(new TreeNode(15));
        root.getRight().setRight(new TreeNode(6));
        root.getLeft().setLeft(new TreeNode(7));
        root.getLeft().setRight(new TreeNode(8));
        travel(root);

    }


    static class TreeNode {
        int value;
        TreeNode left;
        TreeNode right;

        public TreeNode(int value) {
            this.value = value;
        }

        public TreeNode getLeft() {
            return left;
        }

        public void setLeft(TreeNode left) {
            this.left = left;
        }

        public TreeNode getRight() {
            return right;
        }

        public void setRight(TreeNode right) {
            this.right = right;
        }
    }

    public static void travel(TreeNode root) {
        if (root == null) {
            return;
        }
        LinkedList<TreeNode> ld = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        ld.addLast(root);
        int level = 0;
        while (!ld.isEmpty()) {
            int size = ld.size();
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode first = ld.removeFirst();
                temp.add(first.value);
                if (first.left != null) {
                    ld.addLast(first.left);
                }
                if (first.right != null) {
                    ld.addLast(first.right);
                }
            }
            if (level % 2 == 0) {
                res.addAll(temp);
            } else {
                Collections.reverse(temp);
                res.addAll(temp);

            }
            level++;
        }
        res.forEach(System.out::print);
    }
}
